using System.Web.Script.Serialization;
using Microsoft.WindowsAzure.StorageClient;

namespace AzureContrib.WindowsAzure.StorageClient
{
	/// <summary>
	/// Extensions on <see cref="CloudQueueMessage"/>
	/// </summary>
	public static class CloudQueueMessageExtensions
	{
		/// <summary>
		/// 1024 * 8 bytes  = 8KB
		/// </summary>
		public const int MaxMessageBuffer = 8 * 1024;

		private static JavaScriptSerializer JavaScriptSerializer
		{
			get
			{
				return new JavaScriptSerializer { MaxJsonLength = MaxMessageBuffer };
			}
		}

		/// <summary>
		/// Deserialize a <see cref="CloudQueueMessage"/> to an instance of the given type <typeparamref name="T"/>.
		/// </summary>
		/// <typeparam name="T">The type of oject the message is serialized from.</typeparam>
		/// <param name="cloudQueueMessage">The actual message on the queue.</param>
		/// <returns>An instance of type <typeparamref name="T"/></returns>
		public static T Payload<T>(this CloudQueueMessage cloudQueueMessage)
		{
			string toDeserialize = cloudQueueMessage.AsString;
			return JavaScriptSerializer.Deserialize<T>(toDeserialize);
		}

		/// <summary>
		/// Serialize a <see cref="CloudQueueMessage"/> form an instance.
		/// </summary>
		/// <param name="instance">The actual message on the queue.</param>
		/// <returns>A <see cref="CloudQueueMessage"/> serialized from the data in the <paramref name="instance"/></returns>
		public static CloudQueueMessage AsMessage<T>(this T instance)
		{
			var serialized = JavaScriptSerializer.Serialize(instance);
			return new CloudQueueMessage(serialized);
		}
	}
}